import os
import re
import chardet

# kui-novel-arrange
# 奎歪歪的小说整理 脚本
# 段落整理

# 参数设置
directory_path = "txt" # 指定目录路径
indented_paragraph_setting = "    " # 缩进参数
paragraph_spacing_setting = "\n\n" # 段落间距参数


def detect_encoding(file_path):
    with open(file_path, 'rb') as file:
        raw_data = file.read()
        result = chardet.detect(raw_data)
        encoding = result['encoding']
        confidence = result['confidence']
        return encoding, confidence

def format_text_files(directory):
    file_count = 0
    formatted_count = 0
    encoding_table = {}

    # 统计目录下的txt文件数量
    for filename in os.listdir(directory):
        if filename.endswith(".txt"):
            file_count += 1

    # 遍历目录下的txt文件
    for filename in os.listdir(directory):
        if filename.endswith(".txt"):
            filepath = os.path.join(directory, filename)

            # 检测文件编码
            encoding, confidence = detect_encoding(filepath)
            if encoding is None:
                print(f"无法检测文件编码: {filename}")
                continue

            # 记录文件编码到编码表
            if encoding not in encoding_table:
                encoding_table[encoding] = 1
            else:
                encoding_table[encoding] += 1

            with open(filepath, "r", encoding=encoding, errors='ignore') as file:
                content = file.read()

            # 格式整理
            formatted_content = ""
            paragraphs = re.split("\n\n+", content)
            for paragraph in paragraphs:
                indented_paragraph = indented_paragraph_setting + paragraph.strip()
                formatted_content += indented_paragraph + paragraph_spacing_setting

            # 将整理后的内容写回文件
            with open(filepath, "w", encoding=encoding) as file:
                file.write(formatted_content)

            formatted_count += 1

            # 显示整理进度
            print(f"正在整理文件: {filename}")
            print(f"已整理完的文件数量: {formatted_count}/{file_count}")

    print("整理完成！")

    # 打印文件编码表，检查处理后文件编码是否出现问题
    print("文件编码表:")
    for encoding, count in encoding_table.items():
        print(f"编码: {encoding}, 数量: {count}")

format_text_files(directory_path)